package com.codefish.codefishseckill.security;

import com.codefish.codefishseckill.entity.AuthUser;
import com.codefish.codefishseckill.utils.CookieUtil;
import com.codefish.codefishseckill.utils.JwtUtils;
import com.codefish.codefishseckill.utils.ResponseUtil;
import com.codefish.codefishseckill.vo.RespBeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author <a href='https://gitee.com/hzf2281'>codefish</a>
 * @version 1.0.0
 * @since 2022/08/30 下午 05:16
 */
@Component
public class MyAuthSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        //签发jwt
        AuthUser authUser = (AuthUser) authentication.getPrincipal();
        String jwtToken = JwtUtils.issueJwtToken(authUser);
        //将token存入cookie中
        int expireSeconds = (int) (JwtUtils.DEFAULT_EXPIRE_TIME / 1000);
        CookieUtil.setCookie(response, CookieUtil.USER_INFO_KEY, jwtToken, expireSeconds, "/");

        ResponseUtil.out(response, RespBeanFactory.success("登录成功"));
    }

}
